/**
 * Created by Administrator on 15-9-25.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        //app.receivedEvent('deviceready');
        $(document).ready(function(){
           ready();
        });


    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};


//js和cordova插件都加载完成
function ready(){

}

var FOLDER = "sameway";
//var BASE_IMAGEURL = "http://dmimg.wjbb.com.cn:8080";

//页面js对象 和 cordova插件对象全部加载完成  0 拍照  1 本地图片库
function loadImage(flag,folder) {

FOLDER = folder;

  var w=440;
  var h=440;

  var quality = device.platform=="Android"?20:20;
  //  log("device.platform="+device.platform+";quality====="+quality);
  var cameraOptions;
  if(flag==0){
     cameraOptions={
         quality : quality,//ios为了避免部分设备上出现内存错误，quality的设定值要低于50。
         destinationType : Camera.DestinationType.FILE_URI,//FILE_URI,DATA_URL
         sourceType : Camera.PictureSourceType.CAMERA,//CAMERA,SAVEDPHOTOALBUM
         allowEdit : false,
         encodingType : Camera.EncodingType.JPEG//JPEG,PNG
        // targetWidth : w,
        // targetHeight : h
     };
  }else{
     cameraOptions={
         quality : quality,//ios为了避免部分设备上出现内存错误，quality的设定值要低于50。
         destinationType : Camera.DestinationType.FILE_URI,//FILE_URI,DATA_URL
         sourceType : Camera.PictureSourceType.PHOTOLIBRARY,//CAMERA,SAVEDPHOTOALBUM
         allowEdit : false,
         encodingType : Camera.EncodingType.JPEG,//JPEG,PNG
         //targetWidth : w,
        // targetHeight : h
     };
  }


   //拍照并显示在屏幕
   //navigator.camera.getPicture(onLoadImageSuccess, onLoadImageFail, {destinationType: Camera.DestinationType.DATA_URL});

   navigator.camera.getPicture( onCameraSuccess, onCameraError, cameraOptions);
}


//所有获取图片失败都回调此函数
function onCameraError(message) {
    //navigator.notification.alert("拍照失败，原因：" + message, null, "警告");
}



function onCameraSuccess(imageURI){//imageData

    var fileName=imageURI.substr(imageURI.lastIndexOf('/') + 1);
    if(fileName.indexOf("jpg") == -1){
       fileName = fileName + ".jpg"
    }
    var options = new FileUploadOptions();


    if(fileName.indexOf('?') == -1 ){
        options.fileName = fileName;
    }else{
        options.fileName = fileName.substr(0,fileName.indexOf('?'));
    }

     options.fileKey = "file";
     options.mimeType = "image/jpeg";
     //options.mimeType = "multipart/form-data";
     //options.mimeType = "text/plain";
     //options.chunkedMode = false;
//?folder=sameway
//     var params = {};
//     params.fileName = "art";
//     params.fileType = "customer";
//     options.params = params;
     var uri = encodeURI("http://dm.wjbb.com.cn:8080/api/image/upload?folder="+FOLDER);

     var ft = new FileTransfer();

     //navigator.notification.alert("options: " + options, null, "提醒");
      ft.onprogress = function (progressEvt) {//显示上传进度条
        if (progressEvt.lengthComputable) {
            navigator.notification.progressValue(Math.round(( progressEvt.loaded / progressEvt.total ) * 100));
        }
     }
     navigator.notification.progressStart("提醒", "当前上传进度");
     if(FOLDER == "user"){
        ft.upload(imageURI, uri, onFileUploadUserHeaderSuccess, onFileUploadFail, options);
     }else{
        ft.upload(imageURI, uri, onFileUploadSuccess, onFileUploadFail, options);
     }

    // ft.upload(imageURI, uri, onFileUploadSuccess, onFileUploadFail, options);
    // ft.abort();
}

function onCameraError(message){
//navigator.notification.alert("Failed because: " + message, null, "提醒");
//    log('Failed because: ' + message);
}

function onFileUploadSuccess(result){

   navigator.notification.progressStop();//停止进度条
   var testJson = eval("(" + result.response + ")");

   add_car(BASE_IMAGEURL+testJson.url)
}

function onFileUploadUserHeaderSuccess(result){

    $("#photo").attr("src","");
   navigator.notification.progressStop();//停止进度条
   var testJson = eval("(" + result.response + ")");


   $("#photo").attr("src",BASE_IMAGEURL+testJson.url);
}

function onFileUploadFail(error){

navigator.notification.alert("code = "+error.code+";upload error source = " + error.source+";upload error target = " + error.target+"哈哈message===="+error.message, null, "提醒");
    log("code = "+error.code+";upload error source = " + error.source+";upload error target = " + error.target);
}




////拍照成功后回调
//function onLoadImageSuccess(imageURI) {
//
//  // alert(imageURI);
//   //这里的图片经过了base64编码
//   var src = "data:image/jpeg;base64," + imageURI;
//
//   $("#getImage").attr("src", src);
//   $("#getImage").show();
//
//
//   $("#getImagetext").html(src);
//}
//
////所有获取图片失败都回调此函数
//function onCameraError(message) {
//    navigator.notification.alert("拍照失败，原因：" + message, null, "警告");
//}
//
//function loadImageLocal() {
//    //获取本地图片并显示在屏幕
//    navigator.camera.getPicture(onLoadImageLocalSuccess, onLoadImageFail, {
//         destinationType: Camera.DestinationType.FILE_URI,
//         sourceType: Camera.PictureSourceType.PHOTOLIBRARY
//    });
//}
//
////本地图片选择成功后回调此函数
//function onLoadImageLocalSuccess(imageURI) {
//   alert(imageURI);
//   //add_car(imageURI);
//   //$("#getImageLocal").attr("src", imageURI);
//   // $("#getImageLocal").show();
//}
//
//function loadImageUpload() {
//    //拍照上传并显示在屏幕
//    navigator.camera.getPicture(onLoadImageUploadSuccess, onLoadImageFail, {
//        destinationType: Camera.DestinationType.FILE_URI
//    });
//}
//
////图片拍照成功后回调此函数
//function onLoadImageUploadSuccess(imageURI) {
//     //此处执行文件上传的操作，上传成功后执行下面代码
//     var options = new FileUploadOptions(); //文件参数选项
//     options.fileKey = "art";//向服务端传递的file参数的parameter name
//     options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);//文件名
//     options.mimeType = "image/jpeg";//文件格式，默认为image/jpeg
//     var ft = new FileTransfer();//文件上传类
//     ft.onprogress = function (progressEvt) {//显示上传进度条
//        if (progressEvt.lengthComputable) {
//            navigator.notification.progressValue(Math.round(( progressEvt.loaded / progressEvt.total ) * 100));
//        }
//     }
//     navigator.notification.progressStart("提醒", "当前上传进度");
//     ft.upload(imageURI, encodeURI('api/photobook/uploadimg'), function () {
//        navigator.notification.progressStop();//停止进度条
//        $("#getImageUpload").attr("src", imageURI);
//        $("#getImageUpload").show();
//        navigator.notification.alert("文件上传成功！", null, "提醒");
//     }, null, options);
// }


function $$(id){
   var obj=document.getElementById(id);
   return obj;
}

function del(n) {
   $$('ul').removeChild($$(n));
}

function add(id,url) {
   var ul=$$('ul');
   var li= document.createElement("li");
   //var href_a = document.createElement("a");
   //href_a.href="javascript:del('"+id+"');";
   li.innerHTML ="<img style='width:60px;height:60px;' src="+url+"><span class='right-del' onclick=\"del("+id+")\">×</span>";
   li.id=id;
   var index_pic = $$('ul').getElementsByTagName('li').length;
   ul.insertBefore(li,ul.childNodes[index_pic]);  //插入倒数第二个
   // ul.appendChild(li);
}


var index = 1;
function add_car(url){
    if($$('ul').getElementsByTagName('li').length < 13){
        var flag=true;
        var ul_obj=$$('ul').childNodes;
        add(index,url);
        index++;
     }else{
        navigator.notification.alert("只允许加入10张图片!", null, "提醒");
        return;
     }
}

app.initialize();